<!--
 * new page
 * @author: zhaoyahui
 * @since: 2023-09-06
 * Login.vue
-->
<template>
  <div class="body">
    <div class="bg-img">
      <img src="@/assets/images/bg.jpg" />
    </div>
    <div class="loginbox">
      <div class="top">
        <img :src="configKey.logo" class="logoImg" alt="" />
        <p class="title margin-t-2">{{ configKey.name }}</p>
        <p class="slogan margin-t-2">{{ configKey.slogan }}</p>
      </div>
      <div class="main padding-l-2 padding-r-2">
        <div class="login-title">用户登录</div>
        <div class="login-view">
          <a-form ref="formRef" :model="form" auto-label-width :rules="rules">
            <a-form-item field="username" hide-asterisk>
              <a-input size="large" v-model="form.username" placeholder="请输入账户" allow-clear>
                <template #prefix>
                  <span class="iconfont icon-yonghuming"></span>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item field="password" hide-asterisk>
              <a-input-password size="large" v-model="form.password" placeholder="请输入密码" allow-clear>
                <template #prefix>
                  <span class="iconfont icon-mima"></span>
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item field="code" hide-asterisk>
              <a-input size="large" v-model="form.code" placeholder="请输入验证码" allow-clear>
                <template #prefix>
                  <span class="iconfont icon-yanzhengma"></span>
                </template>
              </a-input>
              <img v-show="code" :src="code" alt="" class="code margin-l-1" @click="getCode()" />
            </a-form-item>
            <a-form-item field="name">
              <a-checkbox v-model="form.rememberPwd">记住密码</a-checkbox>
            </a-form-item>
          </a-form>
          <a-button size="large" class="sumbit" type="primary" :loading="userStore.isLogining" @click="login">
            {{ userStore.isLogining ? '登录中' : '确定' }}
          </a-button>
        </div>
      </div>
    </div>
  </div>
  <div class="foot-bar">{{ configKey.copyright }}</div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { encrypt } from '@/utils/jsencrypt'
import auth from '@/api/modules/auth'
import CryptoJS from 'crypto-js'
import Cookies from 'js-cookie'

// 状态管理依赖
import { useUserStore } from '@/store/modules/user'
sessionStorage.setItem('accessToken', '')
sessionStorage.setItem('tagsView', '')

const userStore = useUserStore()
const route = useRoute()

const form = reactive({
  username: '',
  password: '',
  uuid: '',
  code: '',
  rememberPwd: true,
})
const rules = reactive({
  username: [{ required: true, message: '账户不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
})

let code = ref('')
const formRef = ref()
let configKey = ref({ name: '数智化管理协同办公平台', logo: '' })

const getCode = () => {
  auth.code().then((res) => {
    code.value = 'data:image/png;base64,' + res.data.img
    form.uuid = res.data.uuid
  })
}

const login = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      const param = {
        username: form.username,
        password: encrypt(form.password.trim()),
        uuid: form.uuid,
        code: form.code,
      }
      userStore.setIsLogining(true)
      auth
        .login(param)
        .then((res) => {
          let routers = router.getRoutes()
          routers.map((it) => {
            if (it.name) {
              if (!['login', '首页', 'MainPage', 'Error', '404', 'NotFound'].includes(it.name)) {
                router.removeRoute(it.name)
              }
            }
          })
          userStore.login(res.data.access_token)
          const query = route.query
          const redirect = query.redirect ?? '/'
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== 'redirect') {
              acc[cur] = query[cur]
            }
            return acc
          }, {})
          if (form.rememberPwd) {
            Cookies.set('username', form.username, {
              expires: 30,
            })
            Cookies.set(
              'password',
              CryptoJS.AES.encrypt(form.password, '12345678521', {
                expires: 30,
              }),
            )
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
          }
          router.push({ path: redirect, query: otherQueryParams })
        })
        .catch(() => {
          getCode()
          form.code = ''
          userStore.setIsLogining(false)
        })
    }
  })
}
getCode()
if (!userStore.configKey || !Object.keys(userStore.configKey).length) {
  userStore.getConfigKey().then((res) => {
    configKey.value = res.value
  })
}
// 回车查询数据
const keyupSubmit = (e) => {
  let key = null
  if (window.event === undefined) {
    key = e.keyCode
  } else {
    key = window.event.keyCode
  }
  if (key === 13) {
    if (route.path === '/login') {
      //触发的事件
      login()
    }
  }
}
onMounted(() => {
  if (Cookies.get('password')) {
    form.username = Cookies.get('username')
    form.password = CryptoJS.AES.decrypt(Cookies.get('password'), '12345678521').toString(CryptoJS.enc.Utf8)
  } else {
    form.username = ''
    form.password = ''
  }
  window.addEventListener('keydown', keyupSubmit, true) //开启监听键盘按下事件
})
</script>

<style scoped lang="less">
@loginbox-width: 800px;
@loginbox-height: 580px;
@loginbox-image-width: 355px;

.body {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-bg-1);
  .bg-img {
    position: fixed;
    height: 100vh;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      opacity: 0.5;
    }
  }
  .loginbox {
    z-index: 99;
    width: @loginbox-width;
    height: @loginbox-height;
    margin: auto;
    background: var(--color-bg-2);
    box-shadow: @shadow3-center;
    border-radius: @border-radius-large;
    overflow: hidden;
    .top {
      text-align: center;
      width: @loginbox-image-width;
      height: 100%;
      background-size: 100%;
      background: url('@/assets/images/bg_inner.png') center;
      float: left;
      .logoImg {
        width: 160px;
        vertical-align: top;
        margin: 170px auto 10px;
      }
      .title {
        font-size: @font-size-title-3;
        color: @color-white;
        font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
      }
      .slogan {
        font-size: @font-size-title-1;
        color: @color-white;
        font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
      }
    }
    .main {
      width: calc(@loginbox-width - @loginbox-image-width);
      margin: 0 auto;
      float: left;
      display: block;
      position: relative;
      box-sizing: border-box;
      .login-title {
        text-align: center;
        font-size: @font-size-title-1;
        color: @color-text-1;
        padding: @size-16 0;
      }
      :deep(.arco-form-item) {
        flex-wrap: wrap;
        margin-top: @size-3;
      }
      .code {
        width: 107px;
        height: @size-large;
        cursor: pointer;
        border: @border-1 solid @color-border-2;
        box-sizing: border-box;
      }
      .sumbit {
        width: 100%;
      }
    }
  }
}
.foot-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: var(--zczw-layout-footer-height);
  color: @color-text-1;
}
</style>
